package com.example.myble;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final String SERVICE_UUID = "4fafc201-1fb5-459e-8fcc-c5c9c331914b";
    private static final String CHARACTERISTIC_UUID = "beb5483e-36e1-4688-b7f5-ea07361b26a8";
    private BluetoothManager bluetoothManager;
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothGatt bluetoothGatt;
    private static final int REQUEST_ENABLE_BT = 1;
    private static final int PERMISSIONS_REQUEST_CODE = 1001;
    private static final String[] REQUIRED_PERMISSIONS = new String[]{
            Manifest.permission.BLUETOOTH_SCAN,
           Manifest.permission.BLUETOOTH_CONNECT,
            //位置权限
            Manifest.permission.ACCESS_FINE_LOCATION,
           Manifest.permission.ACCESS_COARSE_LOCATION
    };
   // private BluetoothAdapter bluetoothAdapter;
    private BluetoothLeScanner bluetoothLeScanner;
    private ScanCallback scanCallback;
    private BluetoothGattCharacteristic characteristic;
    private Button btnOn,btnOff;
    private boolean connected = false;
   // private BluetoothGatt bluetoothGatt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnOn = findViewById(R.id.btnOn);
        btnOff = findViewById(R.id.btnOff);
        //初始化btnOn为不可点击
//        btnOn.setEnabled(false);
//        //初始化btnOff为不可点击
//        btnOff.setEnabled(false);

        bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (bluetoothManager != null) {
            bluetoothAdapter = bluetoothManager.getAdapter();
        }
        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            Log.e(TAG, "Bluetooth not enabled");
            return;
        }
        // 开始扫描
        //bluetoothAdapter.startLeScan(leScanCallback);
        requestPermissions();
        //添加btnOn处理事件
        btnOn.setOnClickListener(v -> {
            if(!connected) {
                //弹出提示框，显示设备未连接
                Toast.makeText(this, "Device not connected", Toast.LENGTH_SHORT).show();
                return;
            }
            //写入1
            characteristic.setValue(1, BluetoothGattCharacteristic.FORMAT_UINT8, 0);
            bluetoothGatt.writeCharacteristic(characteristic);

        });
        //添加btnOff处理事件
        btnOff.setOnClickListener(v -> {
            //写入0
            if(!connected) {
                //弹出提示框，显示设备未连接
                Toast.makeText(this, "Device not connected", Toast.LENGTH_SHORT).show();
                return;
            }
            characteristic.setValue(0, BluetoothGattCharacteristic.FORMAT_UINT8, 0);
            bluetoothGatt.writeCharacteristic(characteristic);
        });


    }
    private void startBleScan() {
        bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
        scanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                super.onScanResult(callbackType, result);
                // 处理扫描结果
                Log.i("BLE", "Found device: " + result.getDevice().getName());
                //判断设备名是否为空
                if(result.getDevice().getName() == null) {
                    return;
                }else {
                    if (result.getDevice().getName().equals("ESP32BLE")) {
                        // 找到设备，停止扫描
                        bluetoothLeScanner.stopScan(scanCallback);
                    }
                    // 连接设备
                    connectToDevice(result.getDevice());
                }
            }
        };
        // 开始扫描
        bluetoothLeScanner.startScan(scanCallback);
    }
    private void stopBleScan() {
        if (bluetoothLeScanner != null) {
            bluetoothLeScanner.stopScan(scanCallback);
        }
    }
    private void requestPermissions() {
        boolean allGranted = true;
        for (String permission : REQUIRED_PERMISSIONS) {
            allGranted = allGranted && ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
        }

        if (!allGranted) {
            ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, PERMISSIONS_REQUEST_CODE);
        } else {
            // 所有权限已授予，检查蓝牙是否开启
            //打印代码运行到66行了
            Log.i(TAG, "All permissions granted");
            startBleScan();
        }
    }
    private void connectToDevice(BluetoothDevice device) {
        bluetoothGatt = device.connectGatt(this, false, gattCallback);
    }



    private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                Log.i(TAG, "Connected to GATT server.");
                // 发现服务
                bluetoothGatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                Log.i(TAG, "Disconnected from GATT server.");
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.i(TAG, "Services discovered");
                // 获取服务
                BluetoothGattService service = bluetoothGatt.getService(UUID.fromString(SERVICE_UUID));
                if (service != null) {
                    // 获取特征
                    characteristic = service.getCharacteristic(UUID.fromString(CHARACTERISTIC_UUID));
                    if (characteristic != null) {
                        //打印特征值已发现，等待写值
                        Log.i(TAG, "Characteristic found, waiting for write");
                        connected = true;
                        //设置btnOn为可点击
                       // btnOn.setEnabled(true);
                        //设置btnOff为可点击
                        //btnOff.setEnabled(true);
                        // 写入数据到特征值

                    }
                }
            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.i(TAG, "Characteristic written successfully");
            } else {
                Log.w(TAG, "Characteristic write unsuccessful: " + status);
            }
        }
    };
}
